package com.zkk.qqserver.service;

import com.zkk.qqcommon.Message;
import com.zkk.qqcommon.MessageType;
import com.zkk.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * 服务器，在监听9999端口，等待客户端连接，并保持通信
 * */
public class QQServer {

    private ServerSocket ss = null;
    //创建一个集合，存放多个用户用户名密码 模拟数据库
    private static HashMap<String,User> validUsers = new HashMap<>();

    static {//类加载时初始化 validUsers
        validUsers.put("1002",new User("1002","123456"));
        validUsers.put("1003",new User("1003","123456"));
        validUsers.put("1004",new User("1004","123456"));
    }

    //验证用户名和密码方法
    private boolean checkUser(String userId,String pwd){
        User user = validUsers.get(userId);
        if (user == null){//none uid
            return false;
        }
        if (!(user.getPasswd().equals(pwd))){ //pwd error
            return false;
        }
        return true;
    }

    public QQServer() {

        try {
            System.out.println("服务器在9999端口监听...");
            ss = new ServerSocket(9999);

            while (true) {//循环监听
                Socket socket = ss.accept();

                //获取socket相关联的输入流
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                //获取socket相关联的输入流
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

                User u = (User) ois.readObject();//读取客户端发送的user对象

                //替换数据库进行验证
                //创建一个Message对象 准备回复客户端
                Message message = new Message();
                if (checkUser(u.getUserId(), u.getPasswd())){//验证成功
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);

                    //将message对象回复客户端
                    oos.writeObject(message);

                    //创建一个线程，和客户端保持通信，该线程需要持有socket对象
                    ServerConnectClientThread serverConnectClientThread =
                            new ServerConnectClientThread(socket, u.getUserId());
                    serverConnectClientThread.start();

                    //把该线程对象加入到集合中管理
                    ManageClientThreads.addClientThread(u.getUserId(), serverConnectClientThread);

                }else {//验证失败
                    System.out.println("用户 id=" + u.getUserId() + "pwd=" + u.getPasswd() + "请求登录失败");
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(message);
                    socket.close();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
